package cc.rengu.igas.channel.wechat.core.service.trans;


import cc.rengu.igas.channel.wechat.common.constant.WechatParamConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTreeNodeConstant;
import cc.rengu.igas.channel.wechat.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.wechat.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.wechat.core.service.base.MchntService;
import cc.rengu.igas.channel.wechat.facade.bean.ViolationInfo;
import cc.rengu.igas.channel.wechat.facade.request.GetViolationRequest;
import cc.rengu.igas.channel.wechat.facade.response.GetViolationResponse;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.DstChannelCfg;
import cc.rengu.oltp.service.common.entity.DstChannelInfo;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 银行特约商户违规信息查询
 */
public class GetViolationService extends MchntService {
    @Override
    protected Object beforeBizProcess() throws Exception {
        GetViolationRequest getViolationRequest = new GetViolationRequest();
        ConvertUtil.convertOutput(getViolationRequest);
        return getViolationRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        int iReturnCode = 0;

        GetViolationResponse getViolationResponse = new GetViolationResponse();
        GetViolationRequest getViolationRequest = (GetViolationRequest) request;
        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(WechatTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);
        DstChannelInfo dstChannelInfo = (DstChannelInfo) xmlTreeUtil.getXmlTreeObjectValue(WechatTreeNodeConstant.DST_CHANNEL_INFO, DstChannelInfo.class);
        if (!StringUtil.isEmptyOrNull(getViolationRequest.getBeginDate()) && DateUtil.checkDateFormat(getViolationRequest.getBeginDate(), "yyyy-MM-dd")) {
            String newBeginDate = DateUtil.dateStringFormatConvert(getViolationRequest.getBeginDate(), "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss");
            if (!StringUtil.isEmptyOrNull(newBeginDate)) {
                getViolationRequest.setBeginDate(newBeginDate);
            } else {
                getViolationRequest.setBeginDate(getViolationRequest.getBeginDate().concat(" 00:00:00"));
            }
        }


        if (!StringUtil.isEmptyOrNull(getViolationRequest.getEndDate()) && DateUtil.checkDateFormat(getViolationRequest.getEndDate(), "yyyy-MM-dd")) {
            if (DateUtil.compareTime(DateUtil.getCurrentDateTime("yyyy-MM-dd"), getViolationRequest.getEndDate(), "yyyy-MM-dd") <= 0) {
                getViolationRequest.setEndDate(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
            } else {
                String nextDate = DateUtil.getPastOrFutureDayTime(getViolationRequest.getEndDate(), "yyyy-MM-dd", "D", 1);
                String newEndDate = DateUtil.dateStringFormatConvert(nextDate, "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss");
                if (!StringUtil.isEmptyOrNull(newEndDate)) {
                    getViolationRequest.setEndDate(newEndDate);
                } else {
                    getViolationRequest.setEndDate(getViolationRequest.getEndDate().concat(" 23:59:59"));
                }
            }
        }
        if (!StringUtil.isEmptyOrNull(getViolationRequest.getPageIndex())) {
            getViolationRequest.setPageIndex(String.valueOf(Integer.parseInt(getViolationRequest.getPageIndex()) + 1));
        }
        ConvertUtil.convertInput(getViolationRequest);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, getViolationRequest.getHeader().getTxnNum());
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.WX_CHANNEL_NO, dstChannelCfg.getChannelNo());
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.WX_MCHNT_NO, dstChannelCfg.getProviderMchntNo());
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.WX_APP_ID, dstChannelCfg.getAppId());
        xmlTreeUtil.setXmlTreeStringValue("violationRecordsFormat", "json");
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.WX_SIGN_TYPE, WechatParamConstant.HMAC_SHA256_SIGNTYPE);

        //使用默认地址 https://api.mch.weixin.qq.com/risk/getviolation

        iReturnCode = schedule.callService(dstChannelInfo.getDstServiceName(), 0);

        if (xmlTreeUtil.isExist(WechatTreeNodeConstant.DEFINE_HTTP_URL_NODE)) {
            xmlTreeUtil.deleteXmlTreeNode(WechatTreeNodeConstant.DEFINE_HTTP_URL_NODE);
        }

        if (0 != iReturnCode && 98 != iReturnCode) {
            rglog.error("调用微信服<{}>失败，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        } else if (98 == iReturnCode) {
            rglog.error("调用微信服<{}>失败，iReturnCode:<{}>", dstChannelInfo.getDstServiceName(), iReturnCode);
            throw new BizException(RespCodeEnum.TIME_OUT_ERROR.getRespCode(), RespCodeEnum.TIME_OUT_ERROR.getRespDesc());
        }
        ConvertUtil.convertOutput(getViolationResponse);
        String resultCode = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_RESULT_CODE);
        String returnCode = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_RETURN_CODE);
        String returnMsg = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_RETURN_MSG);
        String errCode = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_CODE);
        String errMsg = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_MSG);
        if (!WechatParamConstant.STRING_SUCCESS.equals(resultCode)) {
            if (WechatParamConstant.STRING_SUCCESS.equals(errCode)) {
                //无违规记录
                getViolationResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
                getViolationResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
                rglog.error("调用第三方服务成功,微信返回：respCode=[{}],respDesc=[{}]", errCode, errMsg);
            } else {
                getViolationResponse.setRespCode((null == errCode) ? returnCode : errCode);
                getViolationResponse.setRespDesc((null == errMsg) ? returnMsg : errMsg);
                rglog.error("调用第三方服务失败,respCode=[{}],respDesc=[{}]", getViolationResponse.getRespCode(), getViolationResponse.getRespDesc());
            }
        } else {
            getViolationResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            getViolationResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            String violationRecords = xmlTreeUtil.getXmlTreeStringValue("violationRecords");
            if (violationRecords != null) {
                JSONObject jsonObject = JSON.parseObject(violationRecords);
                getViolationResponse.setTotalSize(jsonObject.getString("total_size"));
                if (Integer.parseInt(jsonObject.getString("total_size")) > 0) {
                    JSONArray jsonArray = jsonObject.getJSONArray("violation_records");
                    List<ViolationInfo> violationInfoList = new ArrayList<>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        ViolationInfo violationInfo = new ViolationInfo();
                        violationInfo.setCompanyName((String) jsonArray.getJSONObject(i).get("company_name"));
                        violationInfo.setHandleMethod((String) jsonArray.getJSONObject(i).get("handle_method"));
                        violationInfo.setHandleState((String) jsonArray.getJSONObject(i).get("handle_state"));
                        violationInfo.setPunishTime((String) jsonArray.getJSONObject(i).get("punish_time"));
                        violationInfo.setSubMchntNo((String) jsonArray.getJSONObject(i).get("sub_mch_id"));
                        violationInfoList.add(violationInfo);
                    }
                    getViolationResponse.setViolationInfoList(violationInfoList);
                }

            }
        }
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        chnlBizResponse.setResult(getViolationResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        GetViolationResponse getViolationResponse = (GetViolationResponse) response.getResult();
        ConvertUtil.convertInput(getViolationResponse);
    }

}
